package com.dhh.activity;

import java.util.ArrayList;
import java.util.List;
import com.dhh.R;
import com.dhh.dao.DataBaseHelper;
import com.dhh.util.CUtil;
import com.dhh.util.manager.WeightManager;
import com.dhh.vo.Weight;
import com.dhh.widget.AmazingAdapter;
import com.dhh.widget.AmazingListView;
import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem.Type;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

public class WeightLogActivity extends GDActivity implements View.OnClickListener {
	private DataBaseHelper db;
	private WeightManager wManager;
	private String cItemId;
	private AmazingListView lsComposer;
	private SectionComposerAdapter adapter;	
	
	@Override  
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
		setActionBarContentView(R.layout.show_food_log);

        db = new DataBaseHelper(getBaseContext());
        db.openDataBase();         
        wManager = new WeightManager(db);
        
		initActionBar();
		initView();
	}
	
	@Override
	public void onStart() {
        super.onStart();     
        initData();
	}
	
	private void initView(){
		lsComposer = (AmazingListView) findViewById(R.id.flComposer);    
        lsComposer.setTextFilterEnabled(true);
		lsComposer.setDivider( null );
		lsComposer.setDividerHeight(1); 
	}
	
	private void initData(){
		adapter = new SectionComposerAdapter();
		List<Pair<String, List<Weight>>> logs = new ArrayList<Pair<String, List<Weight>>>();
		Pair<String, List<Weight>> pair = new Pair<String, List<Weight>>("",wManager.getWeightLog());
		logs.add(pair);
		adapter.setData(logs);
		
		if(adapter.getCount()==0){
			lsComposer.setVisibility(View.GONE);
		}else{
			lsComposer.setVisibility(View.VISIBLE);
			lsComposer.setAdapter(adapter);
//			lsComposer.setOnItemLongClickListener(new OnItemLongClickListener() {
//				@Override
//				public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {	
//					cItemId = ((TextView) view.findViewById(R.id.wl_id)).getText().toString();
//					WeightLogActivity.this.showDialog(0);				
//					return true;
//				}
//			});
		}
	}
	
	private void initActionBar(){
		getActionBar().setTitle(" My Weight");
        getActionBar().setBackgroundColor(Color.rgb(14, 166, 249));
        getActionBar().getChildAt(0).
        	setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(WeightLogActivity.this,HomeActivity.class);	
					startActivity(intent);
				}}); 
        addActionBarItem(Type.Gallery).getItemView()
        .setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(WeightLogActivity.this,WeightChartActivity.class);
				startActivity(intent);
			}}); 
        addActionBarItem(Type.Add).getItemView()
                .setOnClickListener(new OnClickListener(){
					@Override
					public void onClick(View v) {
						WeightLogActivity.this.addWeightDailog("Add Weight").show();
					}}); 
	}
	
	@Override
	public void onClick(View v) {
		
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id){
		case 0:
			return new AlertDialog.Builder(this)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setTitle("Are you sure you want to delete this log?")
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,	int whichButton){
						wManager.removeWeight(cItemId);
						WeightLogActivity.this.initData();
						Toast.makeText(getBaseContext(),"The log has been deleted!", Toast.LENGTH_SHORT).show();
					}
				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int whichButton){}
					}).create();
		}
		
		return null;
	}

	class SectionComposerAdapter extends AmazingAdapter {
		List<Pair<String, List<Weight>>> all = null;
		
		public void setData(List<Pair<String, List<Weight>>> data){
			all = data;
		}

		@Override
		public int getCount() {
			int res = 0;
			for (int i = 0; i < all.size(); i++) {
				res += all.get(i).second.size();
			}
			return res;
		}

		@Override
		public Weight getItem(int position) {
			int c = 0;
			for(int i = 0; i < all.size(); i++) {
				if(position >= c && position < c + all.get(i).second.size()) {
					return all.get(i).second.get(position - c);
				}
				c += all.get(i).second.size();
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		protected void onNextPageRequested(int page) {
		}

		@Override
		protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
			view.findViewById(R.id.header).setVisibility(View.GONE);
		}

		@Override
		public View getAmazingView(int position, View convertView, ViewGroup parent) {
			View res = convertView;
			if (res == null) res = getLayoutInflater().inflate(R.layout.weight_log_item, null);
			TextView date = (TextView) res.findViewById(R.id.wl_date);
			TextView weight = (TextView) res.findViewById(R.id.wl_weight);
			TextView ld = (TextView) res.findViewById(R.id.wl_identify);
			TextView wid = (TextView) res.findViewById(R.id.wl_id);
			
			Weight item = getItem(position);
			date.setText(CUtil.getDate("yyyy-MM-dd", "EEE, MMM dd", item.getDate()));
			ld.setText(item.getDate());
			weight.setText(item.getWeight());
			wid.setText(item.getId());
			
			return res;
		}

		@Override
		public void configurePinnedHeader(View header, int position, int alpha) {
			TextView lSectionHeader = (TextView)header;
			lSectionHeader.setText(getSections()[getSectionForPosition(position)]);
			lSectionHeader.setBackgroundColor(alpha << 24 | (0xbbffbb));
			lSectionHeader.setTextColor(alpha << 24 | (0x000000));
		}
		

		@Override
		public int getPositionForSection(int section) {
			if (section < 0) section = 0;
			if (section >= all.size()) section = all.size() - 1;
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (section == i) { 
					return c;
				}
				c += all.get(i).second.size();
			}
			return 0;
		}

		@Override
		public int getSectionForPosition(int position) {
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (position >= c && position < c + all.get(i).second.size()) {
					return i;
				}
				c += all.get(i).second.size();
			}
			return -1;
		}

		@Override
		public String[] getSections() {
			String[] res = new String[all.size()];
			for (int i = 0; i < all.size(); i++) {
				res[i] = all.get(i).first;
			}
			return res;
		}
		
	}
	
	@Override
    public void onResume(){
    	super.onResume();
        db.openDataBase();       
    }
    
    @Override
	protected void onPause(){
		super.onPause();
		if (db != null) {
			db.close();
		}
	}
    
    @Override
	protected void onStop(){
		super.onStop();
	}
	
	AlertDialog addWeightDailog(String title){
		final LayoutInflater li = LayoutInflater.from(this);
        final View categoryDetailView = li.inflate(R.layout.weight_add_detail, null);		
		
		AlertDialog.Builder builder = new AlertDialog.Builder(WeightLogActivity.this);
		builder.setView(categoryDetailView).setTitle(title).
		setPositiveButton("OK", new DialogInterface.OnClickListener(){		    	 
            @Override
            public void onClick(DialogInterface d, int which) {
            	EditText et = (EditText) categoryDetailView.findViewById(R.id.wa_weight);
            	String weight = et.getText().toString();
            	DatePicker datePicker = (DatePicker) categoryDetailView.findViewById(R.id.wa_date);
            	StringBuffer sb = new StringBuffer();
        		sb.append(datePicker.getYear());
        		sb.append("-");
        		int m = datePicker.getMonth()+1;
        		sb.append(m>10 ? m:"0"+m);
        		sb.append("-");
        		int day = datePicker.getDayOfMonth();
        		sb.append(day>10 ? day:"0"+day);
        		String date = sb.toString();
        		Weight w = new Weight();
        		w.setDate(date);
        		w.setWeight(weight);
        		wManager.addWeightGoal(w);        		
            	d.dismiss();
            	initData();
            }
	    }).
	    setNegativeButton("Cancel", new DialogInterface.OnClickListener(){		    	 
            @Override
            public void onClick(DialogInterface d, int which) {
            	d.dismiss();
            }
	    });
		return builder.create();
	}
}
